package com.yang.auth.handler;

import com.yang.auth.enums.ResponseCodeEnum;
import com.yang.framework.common.exception.biz.BizException;
import com.yang.framework.common.response.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({BizException.class})
    public R handlerBizException(BizException e, HttpServletRequest request) {

        log.error("请求：{} 失败，错误码：{}，错误信息：{}", request.getRequestURI(), e.getErrorCode(), e.getErrorMessage());
        return R.fail(e.getErrorCode(),e.getErrorMessage());
    }

    /**
     * 方法参数校验异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handlerMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String errorCode = ResponseCodeEnum.PARAM_NOT_VALID.getErrorCode();

        StringBuilder sb = new StringBuilder();
        Optional.ofNullable(e.getBindingResult().getFieldErrors()).ifPresent(
                errors -> {
                    for (FieldError error : errors) {
                      sb.append(error.getField())
                            .append(" ")
                            .append(error.getDefaultMessage())
                            .append(",当前值：'")
                            .append(error.getRejectedValue())
                            .append("';");
                    }
                }
        );

        String errorMessage = sb.toString();
        log.error("请求：{} 失败，错误码：{}， 错误信息：{}", request.getRequestURI(), errorCode, errorMessage);

        return R.fail(errorCode, errorMessage);
    }

    /**
     * 捕获非法参数
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({IllegalArgumentException.class})
    public R handlerIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {

        String errorCode = ResponseCodeEnum.PARAM_NOT_VALID.getErrorCode();
        String errorMessage = e.getMessage();

        log.error("请求：{} 失败，错误码：{}，错误i信息：{}", request.getRequestURI(), errorCode, errorMessage);

        return R.fail(errorCode, errorMessage);
    }


    /**
     * 捕获其他异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({Exception.class})
    public R handlerException(Exception e, HttpServletRequest request) {

        log.error("请求：{} 失败，错误信息：{}", request.getRequestURI(), e);
        return R.fail(ResponseCodeEnum.SYSTEM_ERROR);
    }

}
